package com.sky.service.impl;

import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 添加地址列表
     * @param addressBook
     */
    public void addAddress(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.insertAddress(addressBook);
    }

    /**
     * 查看当前用户的地址列表
     */
    public List<AddressBook> listUserAddress() {
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> addressBooks = addressBookMapper.selectUserAddress(addressBook);
        return addressBooks;
    }

    /**
     * 查看默认地址
     * @return
     */
    public AddressBook listDefaultAddress() {
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        AddressBook address = addressBookMapper.selectDefaultAddress(addressBook);
        return address;
    }

    /**
     * 设置默认地址
     * @param addressBook
     */
    public void modifyDefaultAddress(AddressBook addressBook) {
//        先将当前用户的默认地址设为0
        addressBook.setIsDefault(StatusConstant.DISABLE);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.updateDefaultUser(addressBook);

//        再将选中的地址设为默认
        addressBook.setIsDefault(StatusConstant.ENABLE);
        addressBookMapper.updateDefaultAddress(addressBook);
    }

    /**
     * 删除选中的地址
     * @param id
     */
    public void throwOutAddress(Long id) {
        AddressBook addressBook = AddressBook.builder()
                .id(id)
                .userId(BaseContext.getCurrentId())
                .build();
        addressBookMapper.deleteAddress(addressBook);
    }

    /**
     * 根据id查看地址
     * @param id
     * @return
     */
    public AddressBook listAddressById(Long id) {
        AddressBook addressBook = AddressBook.builder()
                .id(id)
                .userId(BaseContext.getCurrentId())
                .build();
        AddressBook address = addressBookMapper.selectAddressById(addressBook);
        return address;
    }

    /**
     * 根据id修改地址
     * @param addressBook
     */
    public void modifyAddress(AddressBook addressBook) {
        log.info("要修改的地址信息为:{}", addressBook);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.updateAddressById(addressBook);
    }
}
